<template>
    <div>
        <div :id="editorName"></div>
    </div>
</template>

<script lang="ts" setup>

import { CommonHelper } from '@/utils/CommonHelper';
import { onMounted, watch, onUnmounted, ref, defineProps, withDefaults, defineEmits } from 'vue'
import UEConfig from './UEConfig';


/**
 * 组件参数
 */
interface IProps {
    /**
     * 绑定值
     */
    modelValue: string;

    /**是否只读 */
    readonly?: boolean;

    /**宽度 */
    width?: number;

    /**高度 */
    height?: number;

    /**模式 default | simple */
    mode?: string
}


const props = withDefaults(defineProps<IProps>(), {
    width: 800,
    height: 300,
    readonly: false,
    mode: "default"
})

const emits = defineEmits(["update:modelValue"]);
let editor: any;
let editorName = ref(`editor_${CommonHelper.getGUIDAsNot()}`);

//防止异步传值无法赋值问题
let asyncLock = false;

onMounted(() => {
    let options = UEConfig.default;
    switch (props.mode) {
        case 'simple':
            options = UEConfig.simple;
            break;
        case 'text':
            options = UEConfig.text;
            break;
    }
    editor = UE.getEditor(editorName.value, {
        toolbars: options,
        enableAutoSave: false, //禁止自动保存
        autoSyncData: false,//自动同步编辑器要提交的数据
        elementPathEnabled: false, //禁止元素路径显示
        initialFrameWidth: props.width  //初始化编辑器宽度,默认1000
        , initialFrameHeight: props.height  //初始化编辑器高度,默认320
    });

    editor.ready(function () {
        if (props.modelValue == "" && asyncLock == false) {
            asyncLock = true;
        }
        editor.setContent(props.modelValue);
        editor.setHeight(props.height);
    });

    editor.addListener("selectionchange", function () {
        emits("update:modelValue", editor.getContent())
    });
})

//卸载组件清理编辑器对象
onUnmounted(() => {
    editor.destroy();
})

//监听值改变
watch(() => props.modelValue, (newValue) => {
    if (asyncLock == true) {
        editor.ready(function () {
            editor.setContent(newValue);
            asyncLock = false;
        });
    }
})
</script>